package org.donhuan.rms.ui.factories;

import java.lang.reflect.Field;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.donghuan.rms.framework.domain.Archive;
import org.donhuan.rms.ui.model.ITreeAndWorkbenchAdapter;
import org.donhuan.rms.ui.model.RmsContentprovider;
import org.donhuan.rms.ui.model.RmsTableLabelProvider;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

public class ContainerFactory {
	public static final int CHECKBOX = 1;

	public static TableViewer createTableViewer(Composite parent, Object input) {
		TableViewer viewer = new TableViewer(parent, SWT.BORDER
				| SWT.FULL_SELECTION | SWT.V_SCROLL);
		parent.setLayout(new FillLayout());
		createTableColumn(viewer.getTable(),
				getAdapter(input).getChildren(input));
		viewer.setContentProvider(new RmsContentprovider());
		viewer.setLabelProvider(new RmsTableLabelProvider());
		viewer.setInput(input);
		return viewer;
	}

	private static ITreeAndWorkbenchAdapter getAdapter(Object o) {

		return (ITreeAndWorkbenchAdapter) Platform.getAdapterManager()
				.getAdapter(o, ITreeAndWorkbenchAdapter.class);
	}

	private static void createTableColumn(Table table, Object[] obj) {
		if (obj.length <= 0 || table == null)
			return;
		TableLayout layout = new TableLayout();
		table.setLayout(layout);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		Field[] fields = createFieldOfObject(obj[0], 0);
		for (int i = 0; i < fields.length; i++) {
			layout.addColumnData(new ColumnWeightData(Integer.divideUnsigned(
					100, fields.length)));
			new TableColumn(table, SWT.NULL, i).setText(fields[i].getName());
		}

	}

	public static Field[] createFieldOfObject(Object obj, int style) {
		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields)
			if (field.getName().endsWith("UID"))//$NON-NLS-N$
				fields = (Field[]) ArrayUtils.removeElement(fields, field);
		return fields;
	}

	public static void main(String[] args) {
		Class clazz = Archive.class;
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields)
			System.out.println(field.getModifiers());
	}
}
